#!/bin/bash

# SFTP connection parameters
SFTP_SERVER="10.83.4.34"
SFTP_PORT="10022"
SFTP_USER="appcheck"
SFTP_PASS="q1w2E#R$"
REMOTE_DIR="/share/share2/fadap"
FILE_NAME="msg.log"
TARGET_STRING="报文数据文件发送成功"

# Check if expect is installed
if ! command -v expect &> /dev/null
then
    echo "Error: expect is not installed. Please install it first."
    echo "On Ubuntu/Debian: sudo apt-get install expect"
    echo "On CentOS/RHEL: sudo yum install expect"
    exit 1
fi

# Temporary file to store content
TEMP_FILE=$(mktemp)

# SFTP script using expect
expect << EOF > "$TEMP_FILE"
set timeout 30
spawn sftp -oPort=$SFTP_PORT $SFTP_USER@$SFTP_SERVER
expect "password:"
send "$SFTP_PASS\r"
expect "sftp>"
send "cd $REMOTE_DIR\r"
expect "sftp>"
send "get $FILE_NAME -\r"
expect "sftp>"
send "exit\r"
expect eof
EOF

# Check if file was read successfully
if [ $? -ne 0 ]; then
    echo "Error: Failed to read file content."
    rm -f "$TEMP_FILE"
    exit 1
fi

# Check for target string
if grep -q "$TARGET_STRING" "$TEMP_FILE"; then
    echo "Found target string in file."
    rm -f "$TEMP_FILE"
    exit 0
else
    echo "Target string not found in file."
    rm -f "$TEMP_FILE"
    exit 1
fi
